package com.anjbo.controller.order;

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;

import com.google.gson.Gson;
import net.sf.json.JSONArray;

import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.JSONException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.anjbo.bean.order.OrderThirdDto;
import com.anjbo.common.MortgageStateEnums;
import com.anjbo.common.RespDataObject;
import com.anjbo.common.RespStatus;
import com.anjbo.common.RespStatusEnum;
import com.anjbo.common.ThirdEnum;
import com.anjbo.controller.common.StatisticsController;
import com.anjbo.service.order.MsOrderService;
import com.anjbo.service.order.OrderThirdService;
import com.anjbo.service.system.UserMortService;
import com.anjbo.utils.ConfigUtil;
import com.anjbo.utils.HttpUtil;
import com.anjbo.utils.JsonUtil;
import com.anjbo.utils.LoginCacheUtil;
import com.anjbo.utils.StringUtil;


@Controller
@RequestMapping("/app/order/yunMortgage")
public class YunOrderController {
	private static final Log log = LogFactory.getLog(YunOrderController.class);
	@Resource
	private OrderThirdService orderThirdService;
	
	@Resource
	private UserMortService userMortService;
	
	@Resource
	private MsOrderService msOrderService;
	
	private final static String YUNURL = ConfigUtil.getStringValue("YUN_URL");
	//private final static String YUNURL = "http://localhost:8085";
	
	/**
	 * 添加云按揭订单
	 * @param request
	 * @param param
	 * @return
	 */
	@RequestMapping("/insertData")
	@ResponseBody
	public RespDataObject<Map<String, Object>> insertData(HttpServletRequest request, @RequestBody Map<String, Object> param){
		new StatisticsController().statistics(request, "3000-5-2");
        RespDataObject<Map<String,Object>> resp = new RespDataObject<Map<String, Object>>();
        Map<String,Object> orderInfo = new HashMap<String, Object>();
        log.info("云按揭请求参数："+new Gson().toJson(param));
        String estateNo = MapUtils.getString(param, "estateNo");
        log.info("estateNo="+estateNo);
        if(StringUtils.isEmpty(estateNo)){
            param.put("estateNo","--");
        }
        String uid = LoginCacheUtil.getUid(MapUtils.getString(param, "sid"), MapUtils.getString(param, "deviceId"));
        log.info("云按揭请求uid："+uid);
		if (StringUtils.isEmpty(uid)) {
			resp.setCode(RespStatusEnum.PARAMETER_ERROR.getCode());
			resp.setMsg(RespStatusEnum.PARAMETER_ERROR.getMsg());
			return resp;
		}
		param.put("uid", uid);
		Map<String,Object> infoMap = userMortService.selectInfoByUid(param);
		if (infoMap == null) {
			resp.setCode(RespStatusEnum.PARAMETER_ERROR.getCode());
			resp.setMsg(RespStatusEnum.PARAMETER_ERROR.getMsg());
			return resp;
		}
		param.put("userMobile", MapUtils.getString(infoMap, "phone"));
		param.put("userName", MapUtils.getString(infoMap, "name"));
		try {
			log.info("============新增云按揭地址"+YUNURL);
			String result = HttpUtil.jsonPost(YUNURL+"/cm/order/app/addOrder", param);
            log.info("云按揭远程调用返回结果："+result);
			log.info("============新增云按揭信息"+result);
			Map<String,Object> maps = (Map<String, Object>) JsonUtil.jsonToMap(result);

			if ("FAIL".equals(MapUtils.getString(maps, "code"))) {
				resp.setCode(MapUtils.getString(maps, "code"));
				resp.setMsg(MapUtils.getString(maps, "msg"));
				return resp;
			}
			orderInfo = JsonUtil.jsonToMap(MapUtils.getString(maps, "data"));
		} catch (Exception e) {
			e.printStackTrace();
			resp.setCode(RespStatusEnum.FAIL.getCode());
			resp.setMsg(RespStatusEnum.FAIL.getMsg());
			return resp;
		}
		orderInfo.put("uid", MapUtils.getString(param, "uid"));
		orderInfo.put("name", MapUtils.getString(param, "custName"));
		orderInfo.put("certificateNo", MapUtils.getString(param, "certificateNo"));
		orderInfo.put("loanAmount", MapUtils.getString(param, "loanAmount"));
		orderInfo.put("type", 12);
		orderInfo.put("progressId", MapUtils.getString(orderInfo, "progressNo"));
		int rv = orderThirdService.add(orderInfo);
		if (rv <= 0) {
			resp.setCode(RespStatusEnum.FAIL.getCode());
			resp.setMsg(RespStatusEnum.FAIL.getMsg());
			return resp;
		}
		resp.setData(orderInfo);
		resp.setCode(RespStatusEnum.SUCCESS.getCode());
		resp.setMsg(RespStatusEnum.SUCCESS.getMsg());

		return resp;
	}

	/**
	 * 云按揭订单详情
	 * @param request
	 * @param param
	 * @return
	 */
	@RequestMapping("/getOrderDetail")
	@ResponseBody
	public RespDataObject<Map<String,Object>> orderDetail(HttpServletRequest request, @RequestBody Map<String, Object> param){
		RespDataObject<Map<String,Object>> resp = new RespDataObject<Map<String,Object>>();
        Map<String,Object> orderInfo = new HashMap<String, Object>();
        
		try {
			String result = HttpUtil.jsonPost(YUNURL
					+ "/cm/order/app/orderDetail", param);
			log.info("============云按揭详情"+result);
			Map<String, Object> maps = (Map<String, Object>) JsonUtil
					.jsonToMap(result);
			if (!"SUCCESS".equals(MapUtils.getString(maps, "code"))) {
				resp.setCode(MapUtils.getString(maps, "code"));
				resp.setMsg(MapUtils.getString(maps, "msg"));
				return resp;
			}
			Map<String,Object> dataMap = JsonUtil.jsonToMap(MapUtils.getString(maps, "data"));
			JSONArray jsonArray = JSONArray.fromObject(MapUtils.getString(dataMap, "orderProgressFlowList"));
			List<Map<String,Object>> dataList = (List<Map<String, Object>>) JSONArray.toCollection(jsonArray,Map.class);
			for (Map<String,Object> dataMaps : dataList) {
				if (dataMaps.get("assessResultMap") == null) {
					dataMaps.remove("assessResultMap");
				} else {
					assembleJson(dataMaps,"assessResultMap");
					continue;
				}
				if (dataMaps.get("loanLendingResultMap") == null) {
					dataMaps.remove("loanLendingResultMap");
				} else {
					assembleJson(dataMaps,"loanLendingResultMap");
					continue;
				}
			}
			orderInfo.put("orderProgressFlowList", dataList);
			
			Map<String,Object> basicMap = JsonUtil.jsonToMap(MapUtils.getString(dataMap, "orderDetail"));
			orderInfo.put("orderDetail", assemble(basicMap));
			
		} catch (Exception e) {
			e.printStackTrace();
			resp.setCode(RespStatusEnum.FAIL.getCode());
			resp.setMsg(RespStatusEnum.FAIL.getMsg());
			return resp;
		}
		resp.setData(orderInfo);
		resp.setCode(RespStatusEnum.SUCCESS.getCode());
		resp.setMsg(RespStatusEnum.SUCCESS.getMsg());
		return resp;
	}
	
	/**
	 * 指定type的订单列表
	 * @param request
	 * @param param
	 * @return
	 */
	@RequestMapping("/getOrderList")
	@ResponseBody
	public RespDataObject<List<OrderThirdDto>> getList(HttpServletRequest request, @RequestBody Map<String, Object> param){
		RespDataObject<List<OrderThirdDto>> resp = new RespDataObject<List<OrderThirdDto>>();
		try {
			String uid = LoginCacheUtil.getUid(
					MapUtils.getString(param, "sid"),
					MapUtils.getString(param, "deviceId"));
			if (StringUtils.isEmpty(uid)) {
				resp.setCode(RespStatusEnum.LOGIN_OVER_TIME.getCode());
				resp.setMsg(RespStatusEnum.LOGIN_OVER_TIME.getMsg());
				return resp;
			}
			param.put("start",MapUtils.getDouble(param,"start").intValue());
			param.put("pageSize",MapUtils.getDouble(param,"pageSize").intValue());
			param.put("uid", uid);
			List<String> typeList = new ArrayList<String>();
			param.put("type", typeList);
			List<OrderThirdDto> orderList = orderThirdService
					.selectOrderList(param);

			for(OrderThirdDto third:orderList){
				String typeName=ThirdEnum.getNameByCode(third.getType());
				third.setTypeName(typeName);
				third.setIsComment(0); //未评价
				if(third.getType()==ThirdEnum.ORDER_TYPE1.getCode()
						||third.getType()==ThirdEnum.ORDER_TYPE5.getCode()||third.getType()==ThirdEnum.ORDER_TYPE10.getCode()){
					third.setIsComment(1);
				}
				String certificateNo = third.getCertificateNo();
				if (certificateNo != null && certificateNo.length() > 14) {
					third.setCertificateNo(StringUtil.doCertificateNo(certificateNo));
				}
				if (12 == third.getType()) {
					third.setLoanAmount(third.getLoanAmount()/10000);
				}
				
				//专为民生订单提供预估可贷与最终贷款金额的查询
				if (13 == third.getType() || 14 == third.getType()) {
					Map<String,Object> paramMap = new HashMap<String, Object>();
					paramMap.put("workorderId", third.getOrderNo());
					if (third.getProgressId() >= 3) {
						paramMap.put("choose", "1");
					} else {
						paramMap.put("choose", "0");
					}
					paramMap = msOrderService.selectLoanAmount(paramMap);
					if (paramMap != null) {
						if (third.getProgressId() >= 3) {
							if (MapUtils.getDouble(paramMap, "loanAmount") != null) {
								third.setLoanAmount(Math.round(MapUtils.getDouble(paramMap, "loanAmount")));
							} else {
								third.setLoanAmount(0);
							}
						} else {
							if (MapUtils.getDouble(paramMap, "loanAmount") != null) {
								third.setLoanAmount(Math.round(MapUtils.getDouble(paramMap, "loanAmount")*0.6));
							} else {
								third.setLoanAmount(0);
							}
						}
					}
				}
			}
			resp.setData(orderList);
		} catch (Exception e) {
			e.printStackTrace();
			resp.setCode(RespStatusEnum.FAIL.getCode());
			resp.setMsg(RespStatusEnum.FAIL.getMsg());
			return resp;
		}
		resp.setCode(RespStatusEnum.SUCCESS.getCode());
		resp.setMsg(RespStatusEnum.SUCCESS.getMsg());
		return resp;
	}

	/**
	 * 征信授权上传照片
	 * @param file
	 * @param paramMap
	 * @return
	 */
	@RequestMapping("/accreditUploadImg")
	@ResponseBody
	public RespStatus accreditUploadImg(
			@RequestParam(value = "file", required = false) MultipartFile file,
			HttpServletRequest request) {
		RespStatus resp = new RespStatus();
		Map<String,Object> paramMap = request.getParameterMap();
		for (Map.Entry<String, Object> entry : paramMap.entrySet()) {
			if (!StringUtils.isEmpty((String) ((Object[]) entry.getValue())[0])) {
				paramMap.put(entry.getKey(),
						(String) ((Object[]) entry.getValue())[0]);
			}
		}
		String uid = LoginCacheUtil.getUid(
				(String)MapUtils.getString(paramMap, "sid"),
				(String)MapUtils.getString(paramMap, "deviceId"));
		if (StringUtils.isEmpty(uid)) {
			resp.setCode(RespStatusEnum.LOGIN_OVER_TIME.getCode());
			resp.setMsg(RespStatusEnum.LOGIN_OVER_TIME.getMsg());
			return resp;
		}
		paramMap.put("uid", uid);
		if (StringUtils.isEmpty(MapUtils.getString(paramMap, "orderNo"))) {
			resp.setCode(RespStatusEnum.PARAMETER_ERROR.getCode());
			resp.setMsg(RespStatusEnum.PARAMETER_ERROR.getMsg());
			return resp;
		}
		String bytestr = getBytes(file);
		if (StringUtils.isEmpty(bytestr)) {
			resp.setCode(RespStatusEnum.FAIL.getCode());
			resp.setMsg("图片转化错误！");
			return resp;
		}
		paramMap.put("file", bytestr);
		String result = HttpUtil.jsonPost(YUNURL
				+ "/cm/order/app/uploadImg", paramMap);
		log.info("============上传照片详情"+result);
		try {
			resp = (RespStatus) JsonUtil.parseJsonToObj(result, RespStatus.class);
		} catch (IOException e) {
			e.printStackTrace();
			resp.setCode(RespStatusEnum.FAIL.getCode());
			resp.setMsg("建行调用错误！");
		}
		return resp;
	}
	
	/**
	 * 图片转二进制数据并编码
	 * @param file
	 * @return
	 */
	public static String getBytes(MultipartFile file){
		try {
			ByteArrayInputStream fis = (ByteArrayInputStream) file.getInputStream();
			ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
			byte[] b = new byte[1000];
			int n;
			while ((n = fis.read(b)) != -1) {
				bos.write(b, 0, n);
			}
			fis.close();
			bos.close();
			return new sun.misc.BASE64Encoder().encodeBuffer(bos.toByteArray());
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
	}
	
	/**
	 * 把map里面指定的数据转成list
	 * @param dataMaps	数据源
	 * @param jsonName	指定数据名称
	 * @throws JSONException
	 */
	private void assembleJson(Map<String,Object> dataMaps,String jsonName) throws JSONException{
		Object assessResult = MapUtils.getObject(dataMaps, jsonName);
		String ssss = JsonUtil.BeanToJson(assessResult);
		Map<String,Object> assessResultMap = JsonUtil.jsonToMap(ssss);
		dataMaps.remove(jsonName);
		List<String> lists = new ArrayList<String>();
		for (Map.Entry<String,Object> entry : assessResultMap.entrySet()) {
			lists.add(MortgageStateEnums.getNameByCode(entry.getKey()) + ":" + entry.getValue());
		}
		dataMaps.put(jsonName, lists);
	}
	
	/**
	 * 组装数据
	 * @param basicMap
	 * @return
	 */
	private List<Map<String,Object>> assemble(Map<String,Object> basicMap) {
		List<Map<String,Object>> datailList = new ArrayList<Map<String,Object>>();
		Map<String,Object> assembleMap = new HashMap<String, Object>();
		assembleMap.put("key", "贷款金额(元)");
		String loanAmount = MapUtils.getString(basicMap, "loanAmount");
		if (!StringUtils.isEmpty(loanAmount)) {
			loanAmount = new BigDecimal(loanAmount).toPlainString();
		}
		assembleMap.put("val", loanAmount);
		datailList.add(assembleMap);
		assembleMap = new HashMap<String, Object>();
		assembleMap.put("key", "提交时间");
		String createTime = MapUtils.getString(basicMap, "createTime");
		if (!StringUtils.isEmpty(createTime)) {
			createTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(new Long(createTime)));
		}
		assembleMap.put("val", createTime);
		datailList.add(assembleMap);
		assembleMap = new HashMap<String, Object>();
		assembleMap.put("key", "物业");
		assembleMap.put("val", MapUtils.getString(basicMap, "property"));
		datailList.add(assembleMap);
		assembleMap = new HashMap<String, Object>();
		assembleMap.put("key", "面积(㎡)");
		assembleMap.put("val", MapUtils.getString(basicMap, "houseArea"));
		datailList.add(assembleMap);
		assembleMap = new HashMap<String, Object>();
		assembleMap.put("key", "成交价(元)");
		String transactionPrice = MapUtils.getString(basicMap, "transactionPrice");
		if (!StringUtils.isEmpty(transactionPrice)) {
			transactionPrice = new BigDecimal(transactionPrice).toPlainString();
		}
		assembleMap.put("val", transactionPrice);
		datailList.add(assembleMap);
		assembleMap = new HashMap<String, Object>();
		assembleMap.put("key", "房产证号");
		assembleMap.put("val", MapUtils.getString(basicMap, "estateNo"));
		datailList.add(assembleMap);
		assembleMap = new HashMap<String, Object>();
		assembleMap.put("key", "姓名（买方）");
		assembleMap.put("val", MapUtils.getString(basicMap, "custName"));
		datailList.add(assembleMap);
		assembleMap = new HashMap<String, Object>();
		assembleMap.put("key", "身份证信息（买方）");
		assembleMap.put("val", StringUtil.doCertificateNo(MapUtils.getString(basicMap, "certificateNo")));
		datailList.add(assembleMap);
		assembleMap = new HashMap<String, Object>();
		assembleMap.put("key", "姓名（卖方）");
		assembleMap.put("val", MapUtils.getString(basicMap, "ownerName"));
		datailList.add(assembleMap);
		assembleMap = new HashMap<String, Object>();
		assembleMap.put("key", "身份证信息（卖方）");
		assembleMap.put("val", StringUtil.doCertificateNo(MapUtils.getString(basicMap, "ownerCertificateNo")));
		datailList.add(assembleMap);
		return datailList;
	}
}
